<template>
  <!-- 项目进度页面 -->
  <el-card>
    <!-- 搜索条件 -->
    <div class="searchForm">
      <el-form :model="searchForm">
        <!-- 第一行 -->
        <span>项目：</span>
        <el-input v-model="searchForm.proName" />
        <span>状态：</span>
        <el-select v-model="searchForm.status" placeholder="请选择">
          <el-option v-for="item in optionState" :key="item.value" :label="item.label" :value="item.value1" />
        </el-select>
        <br />
        <!-- 第二行 -->
        <div class="right">
          <el-button class="search" type="primary" icon="Search" size="small" @click="subSearch">搜索</el-button>
          <el-button class="reset" type="info" icon="RefreshRight" size="small" @click="subReset">重置</el-button>
        </div>
        <br />
        <br>
        <hr style="background-color: #5aa2cc; height: 0.5px; border: none" />
      </el-form>
    </div>
    <!-- 新增项目 -->
    <div>
      <el-button type="primary" @click="handleProject" class="add" size="small">新增</el-button>
      <Dialog ref="projectRef" :projectData="projectData" @submitSend="submitSend"></Dialog>
    </div>
    <hr style="background-color: #e8e8e8; height: 2px; border: none" />
    <!-- 表格 -->
    <div class="common-table">
      <!-- v-if="tableProjectData.length > 0" -->
      <el-table :data="tableProjectData" stripe style="width: 100%" v-if="tableProjectData.length > 0">

        <el-table-column label="项目名称" width="400">
          <template #default="scope">
            <el-tooltip :content="scope.row.proName" placement="top" append-to=".common-table">
              <p class="table-tips table-right">{{ scope.row.proName }}</p>
            </el-tooltip>
          </template>
        </el-table-column>

        <!-- <el-table-column prop="proName" label="项目名称" /> -->
        <el-table-column prop="startTime" label="开始时间" />
        <el-table-column prop="endTime" label="结束时间" />
        <el-table-column label="进度情况">
          <template #default="scope">
            <p class="table-tips table-right">{{ scope.row.status == 1 ? '已完成' : '未完成' }}</p>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template #default="scope">
            <span style="margin-right: 5px;" v-if="compareTime(scope.row.endTime)">
              <el-button v-if="scope.row.status == 0" link type="primary" size="small"
                @click="submitCancel(scope.row)">确定完成</el-button>
              <el-button v-else link type="primary" size="small" @click="submitCancelIssue(scope.row)">取消完成</el-button>
            </span>
            <el-button link type="primary" size="small" @click="submitEdit(scope.row)">编辑</el-button>
            <el-button link type="primary" size="small" @click="submitDel(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-else style="margin-top: 54px;">
        <el-empty description="暂无数据" />
      </div>

      <div class="pager">
        <!-- 分页 -->
        <el-pagination v-show="total > 0" :page-size="searchForm.pageSize" layout="prev, pager, next" :total="total"
          @update:current-page="handlePage" />
      </div>
    

      <!-- 抽屉 -->
      <el-drawer v-model="drawerVisible" :direction="direction" :before-close="drawerClose" :proName="drawerproName">
        <div class="drawer-main">
          <p><span class="tit">标题</span><i>：</i><span class="con">{{ projectDrawerForm.proName }}</span></p>
          <p><span class="tit">发布人</span><i>：</i><span class="con">{{ projectDrawerForm.createName }}</span></p>
          <p><span class="tit">发布时间</span><i>：</i><span class="con">{{ projectDrawerForm.createTime }}</span></p>
          <p><span class="tit">发布状态</span><i>：</i><span class="con">{{ projectDrawerForm.status == 1 ? '已发布' :
            '未发布' }}</span></p>
          <p><span class="tit">上传图片</span><i>：</i><a @click="PreviewDrawerPDF">{{ projectDrawerForm.fileList }}</a>
          </p>
        </div>
      </el-drawer>

      <!-- 弹窗 -->
      <el-dialog v-model="dailyVisible" :proName="dailyproName" width="50%" :before-close="dailyClose"
        :close-on-click-modal="false">
        <div v-loading="btnDisabled" element-loading-text="图片上传中...">
          <el-form ref="ruleFormRef" :model="projectForm" status-icon :rules="rules" label-width="110px">
            <el-form-item label="项目名称" prop="proName" style="margin-left:13px;">
              <el-input v-model="projectForm.proName" type="textarea" resize="none" :rows="2" autocomplete="off"
                placeholder="请输入标题" maxlength="20" :show-word-limit="false" />
            </el-form-item>

            <!-- <el-form-item label="开始时间" prop="startTime" style="margin-left:13px;">
          <el-date-picker style="width:100%;" v-model="projectForm.startTime" value-format="YYYY-MM-DD" type="date"
            append-to=".common-table" placeholder="请选择开始日期" ></el-date-picker>
        </el-form-item>

        <el-form-item label="结束时间" prop="endTime" style="margin-left:13px;">
          <el-date-picker style="width:100%;" v-model="projectForm.endTime" value-format="YYYY-MM-DD" type="date"
            append-to=".common-table" placeholder="请选择结束日期" ></el-date-picker>
        </el-form-item> -->

            <el-form-item label="项目名称" prop="sectionDate" style="margin-left:13px;">
              <el-config-provider :locale="locale">
                <el-date-picker style="width:300px" v-model="projectForm.sectionDate" value-format="YYYY-MM-DD"
                  type="daterange" start-placeholder="请选择开始日期" end-placeholder="请选择结束日期"></el-date-picker>
              </el-config-provider>
            </el-form-item>

            <!-- 上传图片 -->
            <!-- <el-form-item label="上传图片" prop="file" style="margin-left:13px;">
              <el-upload v-model:file-list="projectForm.fileList" action="#" list-type="picture-card" :limit="3"
                :http-request="uploadAction" :before-upload="beforeUpload" accept="image/*" :on-remove="handleRemove"
                :on-exceed="handleExceedCover">
                <el-icon>
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item> -->

            <el-form-item style="margin:15px 0  0 13px;">
              <el-button @click="resetForm()">取消</el-button>
              <el-button type="primary" @click="confirmAdd()">提交</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </div>
  </el-card>
</template>

<script setup>
import locale from "element-plus/lib/locale/lang/zh-cn"; // 中文语言
import { ref, reactive, onMounted } from 'vue'
import { getProjectIdList, getProjectList, addProject, updateProject, delProject, getProgressRelease } from '../../api/progress/index'
import { formatTime } from '../../utils/system/filter'

const defaultTime = new Date(2000, 1, 1, 12, 0, 0);
const total = ref()   //表示数据的总条数

const btnDisabled = ref(false); //按钮禁止

//轮播简讯表格数据
const tableProjectData = ref([

  // {
  //   project: "工地智慧屏",
  //   startTime: "2023-1-1",
  //   endTime: "2025-05-27",
  //   status: 1,
  // },
  // {
  //   project: "宝标",
  //   startTime: "2023-1-1",
  //   endTime: "2023-05-27",
  //   status: 1,
  // },
  // {
  //   project: "工朋",
  //   startTime: "2023-1-1",
  //   endTime: "2023-06-27",
  //   status: 1,
  // },


])




const projectForm = ref({
  id: undefined,
  proName: undefined,//标题
  file: [],//封面url

  createName: JSON.parse(localStorage.getItem("userInfo")).fullName,
  orgId: JSON.parse(localStorage.getItem("userInfo")).orgId,//单位id

  status: 0, //是否完成
  updateTime: undefined,
  sectionDate: [],
  startTime: undefined,  //开始时间
  endTime: undefined,    //结束时间
  fileList: [],//文件暂存
  // currentTime: currentTime //当前时间
})
//重置
function projectFormRest() {
  projectForm.value.id = undefined;
  projectForm.value.proName = undefined;
  projectForm.value.file = [];
  projectForm.value.createName = JSON.parse(localStorage.getItem("userInfo")).fullName,
    projectForm.value.orgId = JSON.parse(localStorage.getItem("userInfo")).orgId;
  projectForm.value.status = 0;
  projectForm.value.updateTime = undefined;
  projectForm.value.fileList = [];
  projectForm.value.sectionDate = [];
  projectForm.value.startTime = undefined;
  projectForm.value.endTime = undefined;
}
//图片校验
const validateFileId = (rule, value, callback) => {
  if (value == "") {
    callback(new Error('请上传图片'))
  } else {
    callback()
  }
}

const rules = reactive({
  proName: [{ required: true, message: '标题不能为空', trigger: 'blur', }, { max: 20, message: '字数超出20字', trigger: 'blur' }],
  // sectionDate: [{ required: true, validator: validateFileId, trigger: "blur" }],
  sectionDate: [{ required: true, message: '时间不能为空', trigger: 'blur', }]
})


const ruleFormRef = ref('');
//编辑(新增)弹窗
const dailyVisible = ref(false)
//抽屉(详情)弹窗
const drawerVisible = ref(false)
const direction = ref('rtl')
//抽屉弹窗
const drawerproName = ref("")
const projectDrawerForm = ref({
  id: undefined,
  proName: undefined,//标题
  file: [],//封面url
  createName: JSON.parse(localStorage.getItem("userInfo")).fullName,
  orgId: JSON.parse(localStorage.getItem("userInfo")).orgId,//单位id
  status: 0, //是否发布
  updateTime: undefined,
  fileList: [],//文件暂存
})
//重置
function projectDrawerFormRest() {
  projectForm.value.id = undefined;
  projectForm.value.proName = undefined;
  projectForm.value.file = [];
  projectForm.value.createName = JSON.parse(localStorage.getItem("userInfo")).fullName,
    projectForm.value.orgId = JSON.parse(localStorage.getItem("userInfo")).orgId;
  projectForm.value.status = 0;
  projectForm.value.updateTime = undefined;
  projectForm.value.fileList = [];
}
//关闭抽屉
const drawerClose = () => {
  projectDrawerFormRest()
  drawerVisible.value = false
}

// 状态选择
const optionState = [
  {
    value1: 1,
    label: "已完成",
  },
  {
    value1: 0,
    label: "未完成",
  },
];
//操作栏数据
const searchForm = reactive({
  proName: undefined,
  status: undefined,
  createTime: [],
  pageNum: 1,//页码
  pageSize: 12,//条数
  // sectionDate: [],
  // updateBeginTime: undefined,
  // updateEndTime: undefined
});


//操作栏重置
const subReset = () => {
  searchForm.proName = undefined
  searchForm.createTime = []
  searchForm.status = undefined
  searchForm.pageNum = 1
  searchForm.pageSize = 12

  getList()
  // searchForm.sectionDate = []
  // searchForm.updateBeginTime = undefined
  // searchForm.updateEndTime = undefined
}

//搜索列表的查询
const subSearch = () => {
  getList()
}

const isEdit = ref(false) //是否为编辑
const dailyproName = ref() //是否为编辑

//新增
const handleProject = () => {
  dailyproName.value = "新增项目进度"
  isEdit.value = false
  dailyVisible.value = true
  // if (JSON.parse(sessionStorage.getItem("zhgd_userList")).orgType != "1") {
  //   approver.value = true
  //   getRoleLeader().then(res => {
  //     approverList.value = res.data
  //     dailyRuleForm.value.approvalUserId = res.data[0].userId
  //   })
  // }
}
const dailyClose = () => {
  projectFormRest()
  isEdit.value = false
  dailyVisible.value = false
}
// //重置表单
const resetForm = () => {
  projectFormRest()
  isEdit.value = false
  dailyVisible.value = false;
}
//编辑
const submitEdit = (row) => {
  dailyproName.value = "编辑项目进度"
  isEdit.value = true
  dailyVisible.value = true
  // projectForm.value = row
   
  getProjectIdList(row.id).then(({ data }) => {
    console.log(data, 'data');
    if (data.code == 200) {
      projectForm.value = data.data
      projectForm.value.sectionDate = []
      console.log(projectForm.value, 'newsForm.value');
      // newsForm.value.fileList = newsForm.value.fileUrl.map(item => {
      //   let obj = {}
      //   obj.url = `${item.prefix}` + `${item.fileName}`
      //   return obj
      //   // obj.url = obj.url.replace(undefined, '')
      // })
      if (projectForm.value.sectionDate) {
        console.log(projectForm.value.sectionDate, 'newsForm.value');
        projectForm.value.sectionDate[0] = projectForm.value.startTime;
        projectForm.value.sectionDate[1] = projectForm.value.endTime;
      }

      // projectForm.value.sectionDate = 
      // console.log(projectForm.value, 'newsForm.value');
    }
  });
}


const tableLoading = ref(false)
//获取新闻进行刷新列表
function getList() {
  // tableProjectData.value = []
  // if (queryParams.sectionDate) {
  //   queryParams.updateBeginTime = queryParams.sectionDate[0];
  //   queryParams.updateEndTime = queryParams.sectionDate[1];
  // }
  tableLoading.value = true;
  getProjectList(searchForm).then(({ data }) => {
    console.log(data.data);
    if (data.code == 200) {
      tableLoading.value = false;
      tableProjectData.value = data.data.list

      total.value = data.data.totalCount

      //图片地址
      // tableList.value.forEach(item => {
      //   if (item.file) {
      //     item.file =  item.file
      //   }
      // })
    }
  })
}


// 点击发布
const submitCancel = (row) => {
  getProgressRelease(row.id, 1).then(({ data }) => {
    if (data.code != 200) {
      ElMessage({
        message: '完成失败',
        type: 'error',
      })
    } else {
      // ElMessage({
      //   message: '',
      //   type: 'success',
      // })
      getList()
    }
  })
}

// 点击取消发布
const submitCancelIssue = (row) => {
  getProgressRelease(row.id, 0).then(({ data }) => {
    if (data.code != 200) {
      ElMessage({
        message: '取消失败',
        type: 'error',
      })
    } else {
      ElMessage({
        message: '取消成功',
        type: 'success',
      })
      getList()
    }
  })
}

// 点击详情
const submitDetail2 = (row) => {

  // row.file.forEach(item => {
  //   fileList.push(item.url)
  // });
  drawerVisible.value = true
  drawerproName.value = "新闻详情"
  projectDrawerForm.value = row
  // let data = {
  //   id: val.id,
  // }


}

// 点击删除
const submitDel = (row) => {
  ElMessageBox.confirm("你确定删除吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      delProject({ id: row.id }).then(({ data }) => {
        console.log(data, 'res');
        if (data.code != 200) {
          ElMessage({
            message: '删除失败',
            type: 'error',
          })
        } else {
          ElMessage({
            message: '删除成功',
            type: 'success',
          })
          getList()
        }
      })
    })
    .catch(() => {
    });
}

//图片接口
const uploadAction = (val) => {
  btnDisabled.value = true;
  let param = new FormData();
  param.append("file", val.file);
  uploadImage(param).then(({ data }) => {
    if (data.code == 200) {
      console.log(data, 'res');
      btnDisabled.value = false // 上传成功之后关闭上传中状态并提示上isLt1M传成功
      // props.dataForm.form.taskInfo.imageUrl.push(data.data[0])
      projectForm.value.file.push(data.data[0])
      if (!data.data[0].url) return
    }
  });
};
const beforeUpload = (file) => {
  //大小小于5M
  const isLt1M = file.size / 1024 / 1024 < 5;
  if (!isLt1M) {
    ElMessage({
      message: "上传图片大小不能超过5MB！",
      type: "warning",
    });
    return false;
  }
  const fileSuffix = file.name
    .substring(file.name.lastIndexOf(".") + 1)
    .toLowerCase();
  // console.log(fileSuffix,'fileSuffix')
  const whiteList = ["png", "jpg", "jpeg"];
  if (whiteList.indexOf(fileSuffix) === -1) {
    ElMessage({
      message: "上传文件只能是图片格式！",
      type: "warning",
    });
    return false;
  }
  return true;
};

//超过限制的回调
const handleExceedCover = (files, fileList) => {
  ElMessage.error({
    message: `上传图片数量超出限制！`,
    type: 'error',
  })
}
const handleRemove = (file) => {

  projectForm.value.file = projectForm.value.file.filter(item => {
    return item.name != file.name
  })
  console.log(projectForm.value.file, 'projectForm.value.file')
  return true;
};

//确定新增/编辑
const confirmAdd = () => {
  if (projectForm.value.sectionDate) {
    projectForm.value.startTime = projectForm.value.sectionDate[0];
    projectForm.value.endTime = projectForm.value.sectionDate[1];
  }
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      //编辑
      if (isEdit.value) {
        updateProject(projectForm.value).then(res => {
          console.log('编辑成功', res);
          dailyVisible.value = false
          projectFormRest()

          ElMessage.closeAll();
          if (res.code == 200) {
            ElMessage({
              message: '编辑成功',
              type: 'success',
            })
          }
          getList();
        })
      } else {
        addProject(projectForm.value).then(res => {
          console.log('新增成功', res);
          dailyVisible.value = false
          projectFormRest()
          ElMessage.closeAll();
          if (res.code == 200) {
            ElMessage({
              message: '新增成功',
              type: 'success',
            })
          }
          getList();
        })
      }
    } else {
      return false
    }
  })
}

//时间比对
function compareTime(endTime) {
  let currentTime = new Date().getTime() //当前时间戳
  let time = new Date(endTime).getTime()

  if (currentTime < time) {

    return true
  } else {
    return false
  }
}

//分页
const handlePage = (val) => {
  searchForm.pageNum = val //更新页码
  getList()
}

onMounted(() => {
  getList()



})
</script>

<style lang="less" scoped>
.searchForm {

  .el-input,
  .el-select {
    width: 180px;
  }

  span {
    font-size: 14px;
    margin-left: 20px;
  }

  .el-button:hover {
    opacity: 0.7;
  }

  .right {
    float: right;
    padding-right: 20px;

    .search {
      margin: 5px;
    }
  }
}

.el-table {
  font-size: 12px;
  --el-table-header-bg-color: #dadada9d;
}

:deep(.el-table .cell) {
  text-align: center;
}

.el-link {
  font-size: 12px;
  font-family: Arial;
  padding-right: 15px;
}

.main-top {
  height: 20vh;
}



.drawer-main {
  width: 100%;
  padding: 0 16px;

  p {
    display: flex;
    font-size: 16px;
    color: #333;
    line-height: 24px;
    margin-bottom: 20px;
    word-break: break-all;
    word-wrap: break-word;

    S span {
      display: inline-block;
    }

    .tit {
      width: 95px;
      text-align: justify;
      text-align-last: justify;
    }

    i {
      display: inline-block;
      width: 30px;
      font-style: normal;
      font-weight: normal;
    }

    a {
      flex: 1;
      font-style: normal;
      font-weight: normal;
      cursor: pointer;
      color: #4286ff;
    }

    .con {
      flex: 1;
    }
  }
}


.table-tips {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis; //超出范围用'...'代替
  white-space: nowrap;
}

.pager {
  display: flex;
  flex-direction: row-reverse;
  // position: absolute;
  // right: 100px;
  // bottom: 50px;

  .pagination-container {
    position: relative;
  }
}
</style>